<template>
  <div class="admin-posts">
    <el-page-header @back="goBack">
      <template #content>
        <span class="text-large font-600 mr-3">内容管理</span>
      </template>
    </el-page-header>

    <!-- 统计卡片 -->
    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="6">
        <el-card shadow="hover">
          <el-statistic title="总动态数" :value="statistics.posts?.total || 0">
            <template #prefix>
              <el-icon><ChatDotRound /></el-icon>
            </template>
          </el-statistic>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <el-statistic title="最近7天" :value="statistics.posts?.recent || 0">
            <template #prefix>
              <el-icon><Clock /></el-icon>
            </template>
          </el-statistic>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <el-statistic title="总评论数" :value="statistics.comments?.total || 0">
            <template #prefix>
              <el-icon><ChatLineRound /></el-icon>
            </template>
          </el-statistic>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <el-statistic title="最近7天评论" :value="statistics.comments?.recent || 0">
            <template #prefix>
              <el-icon><Promotion /></el-icon>
            </template>
          </el-statistic>
        </el-card>
      </el-col>
    </el-row>

    <!-- 标签页 -->
    <el-tabs v-model="activeTab" style="margin-top: 20px;">
      <!-- 动态管理 -->
      <el-tab-pane label="动态管理" name="posts">
        <!-- 操作栏 -->
        <el-card class="action-bar" style="margin-top: 20px;">
          <el-row :gutter="20" align="middle">
            <el-col :span="12">
              <el-input
                v-model="postSearchKeyword"
                placeholder="搜索动态内容、用户名..."
                style="width: 100%; max-width: 500px;"
                clearable
                @input="handlePostSearch"
              >
                <template #prefix>
                  <el-icon><Search /></el-icon>
                </template>
              </el-input>
            </el-col>
            <el-col :span="12" style="text-align: right;">
              <el-checkbox v-model="postRecentOnly" @change="handlePostFilterChange">
                仅显示最近7天
              </el-checkbox>
              <el-button type="info" :icon="Refresh" @click="fetchPosts" style="margin-left: 10px;">
                刷新
              </el-button>
            </el-col>
          </el-row>
        </el-card>

        <!-- 动态表格 -->
        <el-card style="margin-top: 20px;">
          <el-table
            v-loading="postsLoading"
            :data="posts"
            stripe
            style="width: 100%"
          >
            <el-table-column type="index" label="序号" width="80" />
            <el-table-column prop="user.username" label="用户" width="120" />
            <el-table-column prop="content" label="内容" min-width="300" show-overflow-tooltip />
            <el-table-column label="图片" width="100">
              <template #default="scope">
                <span v-if="scope.row.post_images && scope.row.post_images.length > 0">
                  {{ scope.row.post_images.length }} 张
                </span>
                <span v-else>无</span>
              </template>
            </el-table-column>
            <el-table-column label="统计" width="150">
              <template #default="scope">
                <div style="font-size: 12px;">
                  <div>点赞: {{ scope.row.likes_count || 0 }}</div>
                  <div>评论: {{ scope.row.comments_count || 0 }}</div>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="created_at" label="发布时间" width="180">
              <template #default="scope">
                {{ formatDate(scope.row.created_at) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120" fixed="right">
              <template #default="scope">
                <el-button
                  type="danger"
                  size="small"
                  @click="deletePost(scope.row)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <el-pagination
            v-model:current-page="postCurrentPage"
            v-model:page-size="postPageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="postTotal"
            layout="total, sizes, prev, pager, next, jumper"
            style="margin-top: 20px; justify-content: flex-end;"
            @size-change="handlePostSizeChange"
            @current-change="handlePostCurrentChange"
          />
        </el-card>
      </el-tab-pane>

      <!-- 评论管理 -->
      <el-tab-pane label="评论管理" name="comments">
        <!-- 操作栏 -->
        <el-card class="action-bar" style="margin-top: 20px;">
          <el-row :gutter="20" align="middle">
            <el-col :span="12">
              <el-input
                v-model="commentSearchKeyword"
                placeholder="搜索评论内容、用户名..."
                style="width: 100%; max-width: 500px;"
                clearable
                @input="handleCommentSearch"
              >
                <template #prefix>
                  <el-icon><Search /></el-icon>
                </template>
              </el-input>
            </el-col>
            <el-col :span="12" style="text-align: right;">
              <el-checkbox v-model="commentRecentOnly" @change="handleCommentFilterChange">
                仅显示最近7天
              </el-checkbox>
              <el-button type="info" :icon="Refresh" @click="fetchComments" style="margin-left: 10px;">
                刷新
              </el-button>
            </el-col>
          </el-row>
        </el-card>

        <!-- 评论表格 -->
        <el-card style="margin-top: 20px;">
          <el-table
            v-loading="commentsLoading"
            :data="comments"
            stripe
            style="width: 100%"
          >
            <el-table-column type="index" label="序号" width="80" />
            <el-table-column prop="user.username" label="用户" width="120" />
            <el-table-column prop="content" label="评论内容" min-width="300" show-overflow-tooltip />
            <el-table-column prop="post.id" label="动态ID" width="100" />
            <el-table-column prop="created_at" label="发布时间" width="180">
              <template #default="scope">
                {{ formatDate(scope.row.created_at) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120" fixed="right">
              <template #default="scope">
                <el-button
                  type="danger"
                  size="small"
                  @click="deleteComment(scope.row)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <el-pagination
            v-model:current-page="commentCurrentPage"
            v-model:page-size="commentPageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="commentTotal"
            layout="total, sizes, prev, pager, next, jumper"
            style="margin-top: 20px; justify-content: flex-end;"
            @size-change="handleCommentSizeChange"
            @current-change="handleCommentCurrentChange"
          />
        </el-card>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import { ref, onMounted, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Search,
  Refresh,
  ChatDotRound,
  ChatLineRound,
  Clock,
  Promotion
} from '@element-plus/icons-vue'
import TravelAPI from '../api/travel'
import logger from '../utils/logger'

export default {
  name: 'AdminPosts',
  components: {
    Search,
    ChatDotRound,
    ChatLineRound,
    Clock,
    Promotion
  },
  setup() {
    const router = useRouter()
    const store = useStore()
    
    const activeTab = ref('posts')
    const postsLoading = ref(false)
    const commentsLoading = ref(false)
    
    // 动态相关
    const posts = ref([])
    const postSearchKeyword = ref('')
    const postRecentOnly = ref(false)
    const postCurrentPage = ref(1)
    const postPageSize = ref(20)
    const postTotal = ref(0)
    
    // 评论相关
    const comments = ref([])
    const commentSearchKeyword = ref('')
    const commentRecentOnly = ref(false)
    const commentCurrentPage = ref(1)
    const commentPageSize = ref(20)
    const commentTotal = ref(0)
    
    // 统计
    const statistics = ref({
      posts: { total: 0, recent: 0 },
      comments: { total: 0, recent: 0 }
    })

    const isAdmin = computed(() => store.getters.isAdmin)

    const fetchPosts = async () => {
      postsLoading.value = true
      try {
        const params = {
          page: postCurrentPage.value,
          page_size: postPageSize.value
        }

        if (postSearchKeyword.value) {
          params.search = postSearchKeyword.value
        }

        if (postRecentOnly.value) {
          params.recent_only = 'true'
        }

        const data = await TravelAPI.getAdminPosts(params)
        
        if (Array.isArray(data)) {
          posts.value = data
          postTotal.value = data.length
        } else {
          posts.value = data.results || []
          postTotal.value = data.count || 0
        }
      } catch (error) {
        logger.error('获取动态列表失败:', error)
        let errorMessage = '获取动态列表失败'
        if (error.response) {
          const status = error.response.status
          if (status === 401) {
            errorMessage = '登录已过期，请重新登录'
          } else if (status === 403) {
            errorMessage = '没有权限访问动态列表'
          } else if (status === 500) {
            errorMessage = '服务器错误，请稍后重试'
          } else if (error.response.data?.error) {
            errorMessage = error.response.data.error
          } else if (error.response.data?.detail) {
            errorMessage = error.response.data.detail
          }
        } else if (error.message) {
          if (error.message.includes('timeout') || error.message.includes('Network Error')) {
            errorMessage = '网络错误，请检查网络连接'
          }
        }
        ElMessage.error(errorMessage)
      } finally {
        postsLoading.value = false
      }
    }

    const fetchComments = async () => {
      commentsLoading.value = true
      try {
        const params = {
          page: commentCurrentPage.value,
          page_size: commentPageSize.value
        }

        if (commentSearchKeyword.value) {
          params.search = commentSearchKeyword.value
        }

        if (commentRecentOnly.value) {
          params.recent_only = 'true'
        }

        const data = await TravelAPI.getAdminComments(params)
        
        if (Array.isArray(data)) {
          comments.value = data
          commentTotal.value = data.length
        } else {
          comments.value = data.results || []
          commentTotal.value = data.count || 0
        }
      } catch (error) {
        logger.error('获取评论列表失败:', error)
        let errorMessage = '获取评论列表失败'
        if (error.response) {
          const status = error.response.status
          if (status === 401) {
            errorMessage = '登录已过期，请重新登录'
          } else if (status === 403) {
            errorMessage = '没有权限访问评论列表'
          } else if (status === 500) {
            errorMessage = '服务器错误，请稍后重试'
          } else if (error.response.data?.error) {
            errorMessage = error.response.data.error
          } else if (error.response.data?.detail) {
            errorMessage = error.response.data.detail
          }
        } else if (error.message) {
          if (error.message.includes('timeout') || error.message.includes('Network Error')) {
            errorMessage = '网络错误，请检查网络连接'
          }
        }
        ElMessage.error(errorMessage)
      } finally {
        commentsLoading.value = false
      }
    }

    const fetchStatistics = async () => {
      try {
        const [postsStats, commentsStats] = await Promise.all([
          TravelAPI.getPostStatistics(),
          TravelAPI.getCommentStatistics()
        ])
        statistics.value = {
          posts: postsStats,
          comments: commentsStats
        }
      } catch (error) {
        logger.error('获取统计数据失败:', error)
      }
    }

    const handlePostSearch = () => {
      postCurrentPage.value = 1
      fetchPosts()
    }

    const handlePostFilterChange = () => {
      postCurrentPage.value = 1
      fetchPosts()
    }

    const handlePostSizeChange = () => {
      fetchPosts()
    }

    const handlePostCurrentChange = () => {
      fetchPosts()
    }

    const handleCommentSearch = () => {
      commentCurrentPage.value = 1
      fetchComments()
    }

    const handleCommentFilterChange = () => {
      commentCurrentPage.value = 1
      fetchComments()
    }

    const handleCommentSizeChange = () => {
      fetchComments()
    }

    const handleCommentCurrentChange = () => {
      fetchComments()
    }

    const deletePost = async (post) => {
      try {
        await ElMessageBox.confirm(
          `确定要删除这条动态吗？此操作不可恢复！`,
          '确认删除',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        await TravelAPI.deleteAdminPost(post.id)
        ElMessage.success('动态已删除')
        fetchPosts()
        fetchStatistics()
      } catch (error) {
        if (error !== 'cancel') {
          logger.error('删除动态失败:', error)
          let errorMessage = '删除失败'
          if (error.response) {
            const status = error.response.status
            if (status === 401) {
              errorMessage = '登录已过期，请重新登录'
            } else if (status === 403) {
              errorMessage = '没有权限删除此动态'
            } else if (status === 404) {
              errorMessage = '动态不存在'
            } else if (error.response.data?.error) {
              errorMessage = error.response.data.error
            } else if (error.response.data?.detail) {
              errorMessage = error.response.data.detail
            }
          } else if (error.message) {
            errorMessage = error.message
          }
          ElMessage.error(errorMessage)
        }
      }
    }

    const deleteComment = async (comment) => {
      try {
        await ElMessageBox.confirm(
          `确定要删除这条评论吗？此操作不可恢复！`,
          '确认删除',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        await TravelAPI.deleteAdminComment(comment.id)
        ElMessage.success('评论已删除')
        fetchComments()
        fetchStatistics()
      } catch (error) {
        if (error !== 'cancel') {
          logger.error('删除评论失败:', error)
          let errorMessage = '删除失败'
          if (error.response) {
            const status = error.response.status
            if (status === 401) {
              errorMessage = '登录已过期，请重新登录'
            } else if (status === 403) {
              errorMessage = '没有权限删除此动态'
            } else if (status === 404) {
              errorMessage = '动态不存在'
            } else if (error.response.data?.error) {
              errorMessage = error.response.data.error
            } else if (error.response.data?.detail) {
              errorMessage = error.response.data.detail
            }
          } else if (error.message) {
            errorMessage = error.message
          }
          ElMessage.error(errorMessage)
        }
      }
    }

    const formatDate = (date) => {
      if (!date) return ''
      const d = new Date(date)
      return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')} ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
    }

    const goBack = () => {
      router.push('/admin')
    }

    // 监听标签页切换
    watch(activeTab, (newTab) => {
      if (newTab === 'posts' && posts.value.length === 0) {
        fetchPosts()
      } else if (newTab === 'comments' && comments.value.length === 0) {
        fetchComments()
      }
    })

    onMounted(() => {
      if (!isAdmin.value) {
        ElMessage.error('您没有管理员权限')
        router.push('/')
        return
      }
      fetchPosts()
      fetchStatistics()
    })

    return {
      activeTab,
      postsLoading,
      commentsLoading,
      posts,
      postSearchKeyword,
      postRecentOnly,
      postCurrentPage,
      postPageSize,
      postTotal,
      comments,
      commentSearchKeyword,
      commentRecentOnly,
      commentCurrentPage,
      commentPageSize,
      commentTotal,
      statistics,
      isAdmin,
      handlePostSearch,
      handlePostFilterChange,
      handlePostSizeChange,
      handlePostCurrentChange,
      handleCommentSearch,
      handleCommentFilterChange,
      handleCommentSizeChange,
      handleCommentCurrentChange,
      deletePost,
      deleteComment,
      fetchPosts,
      fetchComments,
      formatDate,
      goBack,
      Search,
      Refresh,
      ChatDotRound,
      ChatLineRound,
      Clock,
      Promotion
    }
  }
}
</script>

<style scoped>
.admin-posts {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
  /* 南昌旅游特色：天空蓝渐变背景 */
  background: linear-gradient(135deg, #E3F2FD 0%, #BBDEFB 50%, #90CAF9 100%);
  min-height: 100vh;
}

.admin-posts :deep(.el-card) {
  border-radius: 12px;
  border: none;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}

.admin-posts :deep(.el-card:hover) {
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
}

.admin-posts :deep(.el-statistic) {
  text-align: center;
}

.admin-posts :deep(.el-statistic__head) {
  font-size: 14px;
  color: #909399;
  margin-bottom: 8px;
}

.admin-posts :deep(.el-statistic__number) {
  font-size: 28px;
  font-weight: 600;
  color: #303133;
}

.action-bar {
  margin-bottom: 20px;
}

.admin-posts :deep(.el-tabs__item) {
  font-size: 16px;
  font-weight: 500;
  padding: 0 24px;
}

.admin-posts :deep(.el-tabs__item.is-active) {
  /* 南昌红主题色 */
  color: #C8102E;
}

.admin-posts :deep(.el-tabs__active-bar) {
  background-color: #409eff;
  height: 3px;
}

.admin-posts :deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

.admin-posts :deep(.el-table th) {
  /* 南昌红到滕王阁金渐变 */
  background: linear-gradient(135deg, #C8102E 0%, #D4AF37 100%);
  color: white;
  font-weight: 600;
}

.admin-posts :deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
  background-color: #f8f9fa;
}

.admin-posts :deep(.el-button) {
  border-radius: 6px;
  transition: all 0.3s ease;
}

.admin-posts :deep(.el-button:hover) {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.admin-posts :deep(.el-pagination) {
  margin-top: 20px;
  justify-content: flex-end;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .admin-posts {
    padding: 15px;
  }
}

@media (max-width: 768px) {
  .admin-posts {
    padding: 10px;
  }

  .admin-posts :deep(.el-card) {
    margin-bottom: 15px;
  }

  .admin-posts :deep(.el-table) {
    font-size: 12px;
  }

  .admin-posts :deep(.el-table th),
  .admin-posts :deep(.el-table td) {
    padding: 8px 4px;
  }

  .admin-posts :deep(.el-tabs__item) {
    padding: 0 12px;
    font-size: 14px;
  }

  .admin-posts :deep(.el-pagination) {
    justify-content: center;
    flex-wrap: wrap;
  }
}

@media (max-width: 480px) {
  .admin-posts {
    padding: 8px;
  }

  .admin-posts :deep(.el-statistic__number) {
    font-size: 20px;
  }
}
</style>

